#pragma once
#include"global_var.cpp"
void get_pat(const std::string& patterns_path)
{
    std::fstream vcdfile(patterns_path.c_str(),std::ios::in);
    
    if (!vcdfile.is_open()) 
    {
        std::cout << "get_pat error: vcd file open failed" << std::endl;
        return ;
    }
    std::string cmd;
    int index = 0;
    boost::unordered_flat_map<std::string,std::pair<int,int>> symbol_map;   //symbol -> (idx,len)
    boost::unordered_flat_map<std::size_t,int,size_t_hash> signal_map;      //wire_hash[signal_name] -> idx
    std::string pattern = "";
    for(int i=0,sz=sys_in.size()+sys_out.size();i<sz;++i)
    {
        pattern += 'x';
    }

    while(getline(vcdfile,cmd))
    {
        while(cmd.find("$scope ")==std::string::npos)
            getline(vcdfile,cmd);
        break;
    }
    while (getline(vcdfile,cmd))
    {
        if(cmd=="") continue;
        if(cmd.find("$var ")!=std::string::npos) 
        {
            while(cmd.find("$upscope ")==std::string::npos)
            {
                std::vector<std::string> tmp;
                splitString(cmd,' ',tmp);
                int len = std::stoi(tmp[2]);
                symbol_map[tmp[3]] = std::pair<int,int>(index,len);
                if(len>1)
                {
                    for(int i=len-1;i>=0;--i,++index)
                        signal_map[wire_hash[tmp[4]+'['+std::to_string(i)+']']] = index;
                }
                else signal_map[wire_hash[tmp[4]]] = index++;
                getline(vcdfile,cmd);
            }
            continue;
        }

        if(cmd[0]=='$') continue;
        else if(cmd[0]=='#')
        {   
            for(int i=0,sz=sys_in.size();i<sz;++i)
                patterns[wire_hash[sys_in[i]]] = patterns[wire_hash[sys_in[i]]] + pattern[signal_map[wire_hash[sys_in[i]]]];
            for(int i=0,sz=sys_out.size();i<sz;++i)
                vcd_outputs[wire_hash[sys_out[i]]] = vcd_outputs[wire_hash[sys_out[i]]] + pattern[signal_map[wire_hash[sys_out[i]]]];
            continue;
        }
        else if(cmd[0]=='b')
        {
            std::vector<std::string> tmp;
            splitString(cmd,' ',tmp);
            int idx = symbol_map[tmp[1]].first;
            int length = symbol_map[tmp[1]].second;
            for(int i=0;i<length;++i)
                pattern[idx+i] = tmp[0][1+i];
        }
        else
        {
            auto sig = cmd[1];
            std::string sig_str(1,sig);
            pattern[symbol_map[sig_str].first] = cmd[0];
        }
    }

    for(int i=0,sz=sys_in.size();i<sz;++i)
        patterns[wire_hash[sys_in[i]]] = patterns[wire_hash[sys_in[i]]] + pattern[signal_map[wire_hash[sys_in[i]]]];
    for(int i=0,sz=sys_out.size();i<sz;++i)
        vcd_outputs[wire_hash[sys_out[i]]] = vcd_outputs[wire_hash[sys_out[i]]] + pattern[signal_map[wire_hash[sys_out[i]]]];

    vcdfile.close();
}

